<script setup>// 添加用户
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import http from '@/utils/api.js';

const router = useRouter();

// 表单数据模型
const user = ref({
  username: '',
  password: '',
  email: '',
  gender: '',
  phone: '',
});

// 提交表单数据到后端
const handleSubmit = async () => {
  try {
    if (!user.value.username || !user.value.password || !user.value.email || !user.value.phone) {
      alert('请填写完整的用户信息');
      return;
    }

    const response = await http.post('/user/add', user.value); // 提交数据到后端
    console.log(response.data);
    if (response.code === 200) {
      alert('用户添加成功');
      await router.push('/dashboard'); // 添加成功后跳转回用户列表页面
    } else {
      alert(response.data.message || '添加失败');
    }
  } catch (error) {
    console.error('添加用户失败:', error);
    alert('用户添加失败，请检查网络或后端服务！');
  }
};
</script>

<template>
  <div>
    <el-form :model="user" ref="form" label-width="120px">
      <el-form-item label="用户名">
        <el-input v-model="user.username"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input type="password" v-model="user.password"></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="user.email"></el-input>
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="user.gender" placeholder="请选择性别">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="user.phone"></el-input>
      </el-form-item>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </el-form>
  </div>
</template>

<style scoped>

</style>
